"""
Created on 09-Dec-2009

@author: dexen
"""

import os
import sys
import time
import traceback
import multiprocessing as mp

from dexen.system import util
from dexen.system.base import task as task_base
from dexen.system.base.spec import DexenSpec
from dexen.system.node.master.taskq_mgr import TaskQMgr
from dexen.system.node.master.slave_mgr import MasterCore
from dexen.system.server.info import SlaveInfo, MasterInfo
#===============================================================================
# GLOBALS
#===============================================================================
tq_mgr = None
slave_mgr = None
#===============================================================================
# FUNCTIONS
#===============================================================================
def _initialize(masterdir, task):
    assert isinstance(task, task_base.TaskMeta)
    assert task.type == task_base.InitType
    prevpath = os.getcwd()
    os.chdir(masterdir)                    
    obj = task.get_obj()
    inds = obj.__initialize__()
    #logging.debug("%d inds are being placed into queues", len(inds))
    tq_mgr.set_inds(task.name, inds)
    os.chdir(prevpath)

def _setup_schema(schema_zip, masterdir):
    sys.path.append(masterdir)
    util.unzip(schema_zip, masterdir) # TODO: consider folder structure

def init(spec):
    global tq_mgr
    assert isinstance(spec, DexenSpec)
    print "scheduler->init(), ", spec.tasks
    tq_mgr = TaskQMgr(spec.tasks)
    _setup_schema(spec.schema_zip, spec.masterdir)
    _initialize(spec.masterdir, spec.init_task)
    print "the end of init(spec), ", tq_mgr

def schedule_tasks(spec, master_comm):
    """The scheduler 
    master_comm: the shared object between master and scheduler processes.
    """
    global slave_mgr
    
    master_info = master_comm.get_info()
    slave_mgr = MasterCore(spec, tq_mgr)

    while True:
        try:
            slave_name = master_comm.get_slave()
            slave_mgr.schedule(slave_name)
            slave_mgr.execute()
            
            slaves_info = slave_mgr.get_info()
            master_info.action = slaves_info
            master_comm.set_info(master_info)
            #print "I am in scheduler loop"
            #time.sleep(1)
        except Exception:
            print "exception"   
            print sys.exc_info()
            break
        
    print "I am exiting schedule tasks"
     
def run(spec, master_comm):
    init(spec)
    schedule_tasks(spec, master_comm)

def test_run(spec):
    init(spec)
    global slave_mgr
    
    slave_mgr = MasterCore(spec, tq_mgr)
    print "I am in schedule_tasks init is finished"
    slave_mgr.schedule(["SLAVE1", "SLAVE2"])
    while True:
        try:
            slave_mgr.execute()
            #action = slave_mgr.get_info()
            #print "I am in scheduler loop"
            #time.sleep(1)
        except Exception:
            print traceback.print_exc()
            break
        
    print "I am exiting schedule tasks"    


def main():
    pass

if __name__ == "__main__":
    main()
    
    
    